package org.glut.wechat.chat.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

@Component
public class JwtUtil {

    @Value("${jwt.secret-key}")
    private String jwtSecret;

    @Value("${jwt.expirationMs}")
    private int jwtExpirationMs;

    // 使用用户ID生成Token
    public String generateToken(Integer userId) {
        try {
            System.out.println("开始生成 token，用户ID：" + userId);
            String token = buildToken(userId.toString());
            System.out.println("token 生成成功：" + token);
            return token;
        } catch (Exception e) {
            System.out.println("token 生成失败：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    // 构建Token
    private String buildToken(String subject) {
        return Jwts.builder()
                .subject(subject)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + jwtExpirationMs))
                .signWith(getSignKey())
                .compact();
    }

    // 从Token中获取用户ID
    public Integer getUserIdFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(getSignKey())
                .build()
                .parseClaimsJws(token)
                .getBody();

        return Integer.parseInt(claims.getSubject());
    }

    // 验证Token有效性
    public boolean validateToken(String token) {
        try {
            if (token == null || token.isBlank()) {
                throw new JwtException("空Token");
            }

            if (!token.matches("^[a-zA-Z0-9-_]+(\\.[a-zA-Z0-9-_]+)*$")) {
                throw new JwtException("非法Token格式");
            }

            Jwts.parser()
                    .setSigningKey(getSignKey())
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            System.err.println("JWT验证失败: " + e.getMessage());
            return false;
        }
    }

    // 获取签名密钥
    private Key getSignKey() {
        try {
            byte[] keyBytes = Decoders.BASE64.decode(jwtSecret);
            System.out.println("密钥解码成功，长度：" + keyBytes.length); // 正常应≥32字节（256位）
            return Keys.hmacShaKeyFor(keyBytes);
        } catch (IllegalArgumentException e) {
            System.out.println("密钥解码失败：" + e.getMessage());
            throw e; // 抛出异常，便于排查
        }
    }
}